/**
 * @required async-validator
 * @author guocailee
 */
import AsyncValidator from 'async-validator'
import rules from 'async-validator/lib/rule'
import { t } from '../locale'
import * as util from 'async-validator/lib/util'
/* eslint-disable no-useless-escape */
export const isEmail = (val) => {
  return /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(val)
}

export const isMobile = (val) => {
  return /^1+\d{10}$/.test(val)
}

export const isTel = (val) => {
  return /^(1[3,5,8,7]{1}[\d]{9})|(((400)-(\d{3})-(\d{4}))|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{3,7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$|^([ ]?)$/.test(val)
}

function tel(rule, value, callback, source, options) {
  const errors = []
  const validate = rule.required || (!rule.required && source.hasOwnProperty(rule.field))
  if (validate) {
    if (util.isEmptyValue(value) && !rule.required) {
      return callback()
    } else {
      rules.required(rule, value, source, errors, options)
    }
    if (!isTel(value)) {
      errors.push(t('el.errorMessage.tel'))
    }
  }
  callback(errors)
}

function mobile(rule, value, callback, source, options) {
  const errors = []
  const validate = rule.required || (!rule.required && source.hasOwnProperty(rule.field))
  if (validate) {
    if (util.isEmptyValue(value) && !rule.required) {
      return callback()
    } else {
      rules.required(rule, value, source, errors, options)
    }
    if (!isMobile(value)) {
      errors.push(t('el.errorMessage.mobile'))
    }
  }
  callback(errors)
}

AsyncValidator.register('tel', tel)
AsyncValidator.register('mobile', mobile)